<template>
	<view class="send-coupon-detail">
		<image class="send-coupon-header-img" src="https://biapi.vaubang.cn/UploadFiles/Images/send-coupon-header.png"
			mode="widthFix"></image>
		<view class="coupon-info-box" :class="{'marginTop': falgOpen}">
			<view class="coupon-style-box">
				<image class="coupon-icon-img" src="https://biapi.vaubang.cn/UploadFiles/Images/get-coupon-icon.png"
					mode="widthFix"></image>
				<view class="coupon-name">{{couponInfo.stock_name}}</view>
				<view class="coupon-apply">适用商品范围：{{couponInfo.goods_name}}</view>
				<view class="coupon-date">
					生效时间：{{couponInfo.coupon_use_rule.coupon_available_time.available_begin_time}}
					至
					{{couponInfo.coupon_use_rule.coupon_available_time.available_end_time}}
				</view>
			</view>

			<view class="coupon-get-info-box">
				<view class="coupon-submit-get" v-if="isGetCardShow">
					<view class="get-info-title">个人信息</view>
					<view class="info-input-box">
						<view class="info-input-item">
							<image class="info-input-icon" src="../../static/coupon/get-coupon-icon1.png"
								mode="widthFix">
							</image>
							<input class="info-input-class" type="text" v-model="cusName" placeholder="请输入姓名"
								placeholder-class="placeholderClass">
						</view>

						<view class="info-input-item">
							<image class="info-input-icon" src="../../static/coupon/get-coupon-icon2.png"
								mode="widthFix">
							</image>
							<!-- <input class="info-input-class" type="text" placeholder="请输入车牌号"
								placeholder-class="placeholderClass"> -->
							<input class="info-input-class" type="text" v-model="plateNum" disabled placeholder="请输入车牌号"
								placeholder-class="placeholderClass" @click.stop="openPlate">
						</view>
					</view>

					<view class="sure-get-btn" @click="handleGetCoupon">立即领取</view>
				</view>

				<view class="receivedCard" v-else>
					<text class="receivedCardText">已成功领取!</text>
				</view>



			</view>
			<image class="get-coupon-bg1" src="https://biapi.vaubang.cn/UploadFiles/Images/get-coupon-bg1.png"
				mode="widthFix"></image>
			<image class="get-coupon-bg2" src="https://biapi.vaubang.cn/UploadFiles/Images/get-coupon-bg2.png"
				mode="widthFix"></image>
		</view>

		<view>
			<!-- 普通弹窗 -->
			<uni-popup ref="popup" background-color="#fff">
				<view class="popup-content">
					<view class="popup-title">提示</view>
					<view class="popup-tip">领取后将存入微信卡包中,确认领取？</view>
					<!-- 小程序领券插件 -->
					<send-coupon v-if='showWechatbool' @sendcoupon="getSendCoupon" @userconfirm="redirectuser"
						:sign="sign" :send_coupon_params="send_coupon_params"
						:send_coupon_merchant="send_coupon_merchant">
						<view class="get-btn">确认领取</view>
					</send-coupon>
				</view>
			</uni-popup>
		</view>

		<!-- 引用车牌组件 -->
		<plate-number ref="plate" v-model="plateNum" @showOrHide="showOrHide"></plate-number>
	</view>
</template>

<script>
	import apiRqs from '@/api/api-request.js';
	import getDateTime from '@/common/getDateTime.js';
	import plateNumber from '@/components/plate-number/plateNumber.vue';
	export default {
		components: {
			"send-coupon": "plugin://sendCoupon/send-coupon",
			plateNumber,
		},
		data() {
			return {
				cusName: "",
				plateNum: "",
				tokenInfo: {},
				couponInfo: {},
				showWechatbool: false,
				sign: "",
				send_coupon_params: [],
				send_coupon_merchant: "1655918740",
				userOpenid: "",
				shopid: "",
				falgOpen: false,
				isGetCardShow: true,
			}
		},
		onShow() {
			//初始化
			this.$refs.plate.init();
		},
		onLoad(options) {
			this.handleIsRegistered();
			const tokenInfo = uni.getStorageSync("tokenInfo");
			if (tokenInfo) {
				this.tokenInfo = tokenInfo;
			}
			const couponTokenInfo = uni.getStorageSync("couponTokenInfo");
			// if (couponTokenInfo) {
			// 	this.send_coupon_merchant = couponTokenInfo.SubMchId;
			// 	// this.send_coupon_merchant = "1655918740";
			// }


			if (options.type && options.type == 'share') {
				let stock_id = options.stockId;
				let shop_id = options.shopid;
				this.shopid = shop_id;
				this.send_coupon_merchant = options.send_coupon_merchant;
				this.handleSearchConfirm(stock_id);
			} else {
				const couponInfo = uni.getStorageSync("couponInfo");
				this.couponInfo = couponInfo;
			}
		},

		methods: {
			/**
			 * @desc 车牌选择关闭和打开
			 */
			showOrHide(falg) {
				if (falg) {
					this.chartShow = false;
				} else {
					this.chartShow = true;
					this.falgOpen = false;
				}
			},
			openPlate() {
				this.$refs.plate.show();
				this.falgOpen = true;
			},
			// 获取当前日期戳
			getCurDateNum() {
				const cur_date = getDateTime.dateTimeStr('y-m-d h:i:s');
				const date = cur_date.split(" ")[0];
				const time = cur_date.split(" ")[1];
				const year = date.split("-")[0];
				const month = date.split("-")[1];
				const day = date.split("-")[2];
				const hour = time.split(":")[0];
				const min = time.split(":")[1];
				const sec = time.split(":")[2];
				return year + month + day + hour + min + sec;
			},
			// 分享进入根据stock_id查询卡券明细
			handleSearchConfirm(stock_id) {
				getApp().showLoading();
				apiRqs._handleQueryCoupon(stock_id).then((res) => {
					uni.hideLoading();
					console.log('分享查询结果', res);
					if (res.code == 200 && res.data.resultCode.stateCode == 200) {
						const data = JSON.parse(JSON.stringify(res.data));
						data.coupon_use_rule.coupon_available_time.available_begin_time = data.coupon_use_rule
							.coupon_available_time.available_begin_time.split("T")[0];
						data.coupon_use_rule.coupon_available_time.available_end_time = data.coupon_use_rule
							.coupon_available_time.available_end_time.split("T")[0];
						this.couponInfo = data;
					} else {
						getApp().showToast(res.data.resultCode.errorMessage);
					}
				})
			},
			handleGetCoupon() {
				let {
					cusName,
					plateNum
				} = this;
				// 车牌号正则验证 包含新能源车
				const regExp = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z][A-Z][A-Z0-9]{4}[A-Z0-9挂学警港澳]$/;
				if (cusName == "") {
					getApp().showToast('请输入您的姓名');
					return false;
				} else if (plateNum == "") {
					getApp().showToast('请输入您的车牌号');
					return false;
				} else if (plateNum.length < 7 || !regExp.test(plateNum)) {
					getApp().showToast('请输入正确的车牌号');
					return false;
				} else {
					let that = this;
					that.$refs.plate.close();
					// 绑定用户信息
					let userinfo = {
						"openId": that.userOpenid,
						"lsn": plateNum,
						"name": cusName,
						"shopId": that.tokenInfo.shopId,
						"createTime": getDateTime.getDay(0)
					};
					console.log('用户信息', userinfo);
					getApp().showLoading();
					let p1 = new Promise((resolve, reject) => {
						apiRqs._bindUserInfo(userinfo).then(res => {
							console.log('绑定结果', res);
							if (res.code == 200) {
								resolve();
							} else {
								getApp().showToast(res.msg);
								return false;
							}
						})
					})

					p1.then(() => {
						let Randnum = '';
						for (var i = 0; i < 10; i++) {
							Randnum += Math.ceil(Math.random() * 10);
						};
						let q = {
							subMchId: that.send_coupon_merchant,
							signParaDto: [{
									"key": "out_request_no0",
									"val": that.send_coupon_merchant + Randnum
								},
								{
									"key": "send_coupon_merchant",
									"val": that.send_coupon_merchant
								},
								{
									"key": "stock_id0",
									"val": that.couponInfo.stock_id
								}
							]
						};
						console.log("获取Sign签名请求数据", q);
						// 获取Sign签名
						apiRqs._getSign(q).then(res => {
							uni.hideLoading();
							console.log('获取签名结果', res);
							if (res.code == 200) {
								that.sign = res.data; // 获取签名
								that.send_coupon_params = [{ // 发券插件的发券参数
									"stock_id": that.couponInfo.stock_id, // 批次号
									"out_request_no": that.send_coupon_merchant +
										Randnum, // 返回的随机数
									"create_coupon_merchant": that.send_coupon_merchant
								}];
								console.log("签名完成后领券参数 params", that.send_coupon_params);
								that.$refs.popup.open('bottom'); // 打开弹窗
								that.showWechatbool = true; // 打开 领取插件
							} else {
								getApp().showToast(res.msg);
							}
						}).catch(err => {
							console.log('err', err)
						})
						// uni.hideLoading();
						// that.send_coupon_params = [{ // 发券插件的发券参数
						// 	"stock_id": that.couponInfo.stock_id, // 批次号
						// 	"out_request_no": Randnum // 后读返回的随机数
						// }];
						// that.$refs.popup.open('bottom'); // 打开弹窗
						// that.showWechatbool = true; // 打开 领取插件
					})
				}
			},
			// 小程序发券插件API
			getSendCoupon(res) {
				let that = this;
				console.log('小程序发券插件res', res);
				if (res.detail.errcode == 'OK') {
					if (res.detail.send_coupon_result[0].code == 'SUCCESS') {
						that.showWechatbool = false;
						that.isGetCardShow = false;
						that.$refs.popup.close();
						uni.showToast({
							title: '领取成功',
							icon: 'success',
							duration: 2000,
						})
						setTimeout(() => {
							uni.navigateBack();
						}, 2000)
					} else {
						uni.showModal({
							title: '领取失败',
							content: res.detail.send_coupon_result[0].message,
							showCancel: false,
							success: function(res) {
								that.showWechatbool = false;
								that.$refs.popup.close();
							}
						})
					}
				} else {
					// uni.showToast({
					//  title: '领取失败',
					//  icon: 'none'
					// })
					that.showWechatbool = false
					that.$refs.popup.close();
				}
			},
			redirectuser(res) {
				console.log('@userconfirm', res);
			},
			// 验证是否注册
			handleIsRegistered() {
				var that = this;
				uni.login({
					provider: "weixin",
					success(loginRes) {
						console.log('loginRes', loginRes);
						let code = loginRes.code;
						uni.request({
							url: "https://biapi.vaubang.cn/api/v1/WxOpen/Pay/Login?code=" +
								code,
							method: "post",
							header: {
								"content-type": "application/json;charset=utf-8;"
							},
							success(res) {
								console.log('卡券登陆信息', res);
								// 当登录者已经绑定了openid时，直接保存登录信息返回的token以及公司信息
								if (res.data.code == 200) {
									uni.setStorageSync("isLogin", true);
									uni.setStorageSync('userOpenid', res.data.data.openid);
									getApp().globalData.userOpenid = res.data.data.openid;
									that.userOpenid = res.data.data.openid;
								}
							},
							fail(err) {
								console.log(err);
							}
						})
					}
				})
			},
			// 分享给好友
			onShareAppMessage() {
				return this.getShareData();
			},
			getShareData() {
				let title = `赠您一张超值礼品券，点击查看详情！`;
				let imageUrl = "/static/coupon/share-coupon.png";
				let path = '/packageD/coupon/send-coupon-detail?type=share&stockId=' + this.couponInfo.stock_id +
					'&shopid=' + this.tokenInfo.shopId + '&send_coupon_merchant=' + this.send_coupon_merchant;
				return {
					title,
					imageUrl,
					path,
				};
			},
		},
		onHide() {
			//恢复初始化
			this.plateNum = '';
		}
	}
</script>

<style lang="less">
	page {
		background-color: rgba(247, 238, 227, 1);
	}

	.send-coupon-detail {
		.send-coupon-header-img {
			width: 100%;
			background-color: transparent;
		}

		.coupon-info-box {
			border: 1px solid rgba(255, 165, 61, 1);
			border-radius: 10px;
			margin: -7px 20px 0 20px;
			position: relative;

			&.marginTop {
				margin-top: -200px;
			}

			.coupon-style-box {
				margin: 30px 20px;
				background: linear-gradient(135deg, #FFFAF4 0%, #FFF6EC 100%);
				box-shadow: 0px 4px 4px 0px rgba(255, 180, 93, 0.2);
				border-radius: 10px;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 20px;
				box-sizing: border-box;

				.coupon-icon-img {
					width: 48px;
					height: 48px;
					border-radius: 50%;
				}

				.coupon-name {
					font-size: 22px;
					color: rgba(244, 147, 33, 1);
					font-weight: 500;
					margin-top: 10px;
				}

				.coupon-apply {
					font-size: 12px;
					color: rgba(0, 0, 0, 0.50);
					margin-top: 5px;
				}

				.coupon-date {
					font-size: 10px;
					color: rgba(0, 0, 0, 0.50);
					margin-top: 5px;
				}
			}

			.coupon-get-info-box {
				margin: 30px 20px;
				background: linear-gradient(135deg, #FFFAF4 0%, #FFF6EC 100%);
				box-shadow: 0px 4px 4px 0px rgba(255, 180, 93, 0.2);
				border-radius: 10px;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 20px;
				box-sizing: border-box;

				.coupon-submit-get {
					width: 100%;
				}

				.receivedCard {
					width: 100%;
					text-align: center;

					.receivedCardText {
						font-size: 16px;
						color: rgba(244, 147, 33, 1);
						font-weight: 500;
					}
				}

				.get-info-title {
					width: 100%;
					text-align: center;
					font-size: 16px;
					color: rgba(244, 147, 33, 1);
					font-weight: 500;
				}

				.info-input-box {
					width: 100%;
					margin-top: 20px;

					.info-input-item {
						width: 100%;
						height: 44px;
						display: flex;
						align-items: center;
						padding: 0px 10px;
						box-sizing: border-box;
						border-radius: 4px;
						border: 1px solid rgba(244, 147, 33, 1);
						background-color: transparent;

						&:last-child {
							margin-top: 10px;
						}

						.info-input-icon {
							width: 18px;
							flex: 0 0 18px;
							height: 18px;
						}

						.info-input-class {
							flex: 1;
							min-width: 0;
							border: none;
							font-size: 12px;
							color: #666;
							margin-left: 10px;
						}

						.placeholderClass {
							color: #ddd;
						}
					}
				}

				.sure-get-btn {
					width: 100%;
					text-align: center;
					height: 36px;
					line-height: 36px;
					background-color: rgba(255, 165, 61, 1);
					box-shadow: inset 0px 4px 7px 0px rgba(255, 255, 255, 0.33);
					border-radius: 40px;
					font-size: 14px;
					font-weight: 500;
					color: #fff;
					margin-top: 20px;
				}
			}

			.get-coupon-bg1 {
				position: absolute;
				left: 0;
				top: 45%;
				width: 37px;
			}

			.get-coupon-bg2 {
				position: absolute;
				bottom: -20px;
				right: 27px;
				width: 50px;
			}
		}

		.popup-content {
			.popup-title {
				width: 100%;
				text-align: center;
				font-size: 18px;
				color: rgba(0, 0, 0, 1);
				margin-top: 20px;
			}

			.popup-tip {
				width: calc(100% - 40px);
				font-size: 14px;
				color: rgba(0, 0, 0, 0.3);
				text-align: center;
				margin: 20px;
			}

			.get-btn {
				width: 120px;
				text-align: center;
				height: 36px;
				line-height: 36px;
				background-color: rgba(255, 165, 61, 1);
				box-shadow: inset 0px 4px 7px 0px rgba(255, 255, 255, 0.33);
				border-radius: 40px;
				font-size: 14px;
				font-weight: 500;
				color: #fff;
				margin: 30px auto;
			}
		}
	}
</style>